#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

#include <stdarg.h>

int main(int argc, char* argv[])
{
	if (argc > 1) fprintf(2,"it's no need to enter param\n");

	//管道1，数据从父进程流向子进程，0为读端，1为写端
	int pipe_fdp[2];
	//管道2，数据从子进程流向父进程，0为读端，1为写端
	int pipe_fdc[2];
	
	//创建管道
	if (pipe(pipe_fdp) == -1 || pipe(pipe_fdc) == -1)
	{
		printf("pipe error");
		exit(1);
	}
	
	int pid = fork(); //子进程继承父进程，从此开始

	if (pid == -1)
	{
		printf("fork error");
		exit(1);
	}

	if (pid == 0)
	{
		//紫禁城

		//管道是单通的，关闭不用的端口防止阻塞
		close(pipe_fdp[1]);
		close(pipe_fdc[0]);
		
		int cid = getpid();
		char buff[1];
		if( read(pipe_fdp[0], buff, sizeof(buff)) >= 1 )
		{
			fprintf(2, "%d: received ping\n", cid);

			char *msgc = "y";
			write(pipe_fdc[1], msgc, strlen(msgc) + 1);
		}
		else {
			fprintf(2, "error child read...");
			exit(1);
		}

		close(pipe_fdp[0]);
		close(pipe_fdc[1]);

		exit(0);
	}

	else 
	{
		//父进程
		close(pipe_fdp[0]);
		close(pipe_fdc[1]);

		char* msgp = "y";
		write(pipe_fdp[1], msgp, strlen(msgp) + 1);
		
		int fid = getpid();
		char buf[1];
		if (read(pipe_fdc[0], buf, sizeof(buf)) >= 1)
		{
			fprintf(2, "%d: received pong\n", fid);
		}

		close(pipe_fdp[1]);
		close(pipe_fdc[0]);
		
		wait((int*)0); //等待子进程结束
		exit(0);
	}

	exit(0);
}




